{% extends 'base.html' %}

{% block title %}Brother PT-9500PC 标签设计器{% endblock %}

{% block extra_css %}
<!-- 确保Bootstrap CSS加载 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">

<style>
    /* 重置基础样式，确保优先级 */
    * {
        box-sizing: border-box;
    }
    body {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
        margin: 0 !important;
        padding: 0 !important;
    }
    
    .designer-container {
        padding: 20px 0;
        min-height: 100vh;
    }
    
    .designer-card {
        background: rgba(255, 255, 255, 0.95) !important;
        backdrop-filter: blur(10px) !important;
        border-radius: 16px !important;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1) !important;
        border: 1px solid rgba(255, 255, 255, 0.2) !important;
        margin-bottom: 0 !important;
    }
    
    .designer-header {
        background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
        color: white;
        padding: 25px;
        border-radius: 16px 16px 0 0;
    }
    
    .designer-title {
        font-size: 24px;
        font-weight: 700;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .designer-subtitle {
        opacity: 0.9;
        margin: 8px 0 0 0;
    }
    
    .designer-body {
        padding: 25px;
    }
    
    .config-section {
        background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%) !important;
        border: 2px solid #0ea5e9 !important;
        border-radius: 12px !important;
        padding: 20px !important;
        margin-bottom: 25px !important;
    }
    
    .section-title {
        color: #2563eb;
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .orientation-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 15px;
        margin-bottom: 20px;
    }
    
    .orientation-card {
        background: white;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        padding: 15px;
        cursor: pointer;
        transition: all 0.2s ease;
        text-align: center;
    }
    
    .orientation-card:hover {
        border-color: #2563eb;
        transform: translateY(-2px);
    }
    
    .orientation-card.selected {
        border-color: #059669;
        background: linear-gradient(135deg, #ecfdf5 0%, #f0fdf4 100%);
    }
    
    .orientation-icon {
        font-size: 24px;
        color: #2563eb;
        margin-bottom: 8px;
    }
    
    .field-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 12px;
        margin-bottom: 20px;
    }
    
    .field-card {
        background: white;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        padding: 12px;
        cursor: pointer;
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .field-card:hover {
        border-color: #2563eb;
    }
    
    .field-card.selected {
        border-color: #059669;
        background: linear-gradient(135deg, #ecfdf5 0%, #f0fdf4 100%);
    }
    
    .field-icon {
        width: 32px;
        height: 32px;
        background: #f8fafc;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #2563eb;
    }
    
    .preview-section {
        background: white;
        border: 2px solid #e5e7eb;
        border-radius: 12px;
        padding: 20px;
        text-align: center;
        margin-bottom: 20px;
    }
    
    .preview-label {
        background: #ffffff;
        border: 1px solid #d1d5db;
        border-radius: 4px;
        padding: 8px;
        font-family: 'Courier New', monospace;
        font-size: 9px;
        line-height: 1.2;
        margin: 0 auto 15px;
        position: relative;
        display: inline-block;
    }
    
    .preview-label.portrait {
        width: 100px;
        height: 150px;
    }
    
    .preview-label.landscape {
        width: 150px;
        height: 100px;
    }
    
    .preview-qr {
        position: absolute;
        top: 4px;
        right: 4px;
        width: 20px;
        height: 20px;
        background: #f3f4f6;
        border: 1px solid #d1d5db;
        border-radius: 2px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 6px;
    }
    
    .btn-action {
        width: 100%;
        padding: 12px;
        border: none;
        border-radius: 8px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
    }
    
    .btn-primary {
        background: #2563eb;
        color: white;
    }
    
    .btn-success {
        background: #059669;
        color: white;
    }
    
    .btn-warning {
        background: #d97706;
        color: white;
    }
    
    .btn-action:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
    
    .form-control, .form-select {
        width: 100%;
        padding: 10px 12px;
        border: 2px solid #e5e7eb;
        border-radius: 6px;
        margin-bottom: 15px;
        font-size: 14px;
    }
    
    .form-control:focus, .form-select:focus {
        outline: none;
        border-color: #2563eb;
        box-shadow: 0 0 0 0.2rem rgba(37, 99, 235, 0.25);
    }
    
    .form-label {
        font-weight: 600;
        color: #374151;
        margin-bottom: 5px;
    }
    
    .breadcrumb {
        background: transparent;
        padding: 0;
    }
    
    .breadcrumb-item + .breadcrumb-item::before {
        color: rgba(255, 255, 255, 0.7);
    }
    
    .breadcrumb-item a {
        color: rgba(255, 255, 255, 0.9);
        text-decoration: none;
    }
    
    .breadcrumb-item a:hover {
        color: white;
    }
    
    .breadcrumb-item.active {
        color: white;
    }
    
    /* 修复容器和响应式布局 */
    .container {
        max-width: 1200px;
    }
    
    @media (max-width: 768px) {
        .designer-container {
            padding: 10px 0;
        }
        
        .designer-body {
            padding: 15px;
        }
        
        .field-grid {
            grid-template-columns: 1fr;
        }
        
        .orientation-grid {
            grid-template-columns: 1fr;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="designer-container" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px 0;">
    <div class="container" style="max-width: 1200px;">
        <nav aria-label="breadcrumb" class="mb-4">
            <ol class="breadcrumb" style="background: transparent; padding: 0;">
                <li class="breadcrumb-item"><a href="{% url 'assets:index' %}" style="color: rgba(255, 255, 255, 0.9); text-decoration: none;">首页</a></li>
                <li class="breadcrumb-item"><a href="{% url 'assets:label_template_list' %}" style="color: rgba(255, 255, 255, 0.9); text-decoration: none;">标签模板</a></li>
                <li class="breadcrumb-item active" style="color: white;">PT-9500PC 设计器</li>
            </ol>
        </nav>

        <div class="row">
            <div class="col-lg-8">
                <div class="designer-card" style="background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(10px); border-radius: 16px; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); margin-bottom: 0;">
                    <div class="designer-header" style="background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%); color: white; padding: 25px; border-radius: 16px 16px 0 0;">
                        <h1 class="designer-title" style="font-size: 24px; font-weight: 700; margin: 0; display: flex; align-items: center; gap: 10px;">
                            <i class="fas fa-print"></i>
                            Brother PT-9500PC 标签设计器
                        </h1>
                        <p class="designer-subtitle">专为Brother PT-9500PC标签打印机优化</p>
                    </div>
                    
                    <div class="designer-body">
                        <form id="label-form" method="post">
                            {% csrf_token %}
                            
                            <!-- 打印机配置 -->
                            <div class="config-section">
                                <h3 class="section-title">
                                    <i class="fas fa-cog"></i>
                                    打印机配置
                                </h3>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <label class="form-label">标签宽度</label>
                                        <select class="form-select" id="label-width" name="label_width">
                                            <option value="6mm">6mm</option>
                                            <option value="9mm">9mm</option>
                                            <option value="12mm">12mm</option>
                                            <option value="18mm" selected>18mm</option>
                                            <option value="24mm">24mm</option>
                                            <option value="36mm">36mm</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">字体大小</label>
                                        <select class="form-select" id="font-size" name="font_size">
                                            <option value="small">小 (8px)</option>
                                            <option value="medium" selected>中 (10px)</option>
                                            <option value="large">大 (12px)</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <label class="form-label">打印方向</label>
                                <div class="orientation-grid">
                                    <div class="orientation-card selected" data-orientation="portrait">
                                        <input type="radio" name="orientation" value="portrait" checked style="display: none;">
                                        <div class="orientation-icon">
                                            <i class="fas fa-mobile-alt"></i>
                                        </div>
                                        <div><strong>纵向</strong></div>
                                        <small class="text-muted">适合长文本</small>
                                    </div>
                                    <div class="orientation-card" data-orientation="landscape">
                                        <input type="radio" name="orientation" value="landscape" style="display: none;">
                                        <div class="orientation-icon">
                                            <i class="fas fa-tablet-alt"></i>
                                        </div>
                                        <div><strong>横向</strong></div>
                                        <small class="text-muted">适合宽标签</small>
                                    </div>
                                </div>
                            </div>

                            <!-- 基本信息 -->
                            <div class="mb-4">
                                <h3 class="section-title">
                                    <i class="fas fa-info-circle"></i>
                                    基本信息
                                </h3>
                                <input type="text" class="form-control" id="template-name" name="name" 
                                       placeholder="模板名称" required>
                                <textarea class="form-control" id="template-description" name="description" 
                                          rows="2" placeholder="模板描述（可选）"></textarea>
                                <div class="row mt-3">
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" id="company-header" name="company_header" 
                                               placeholder="公司抬头（可选）">
                                    </div>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" id="lost-notice" name="lost_notice" 
                                               placeholder="遗失标签提示（可选）">
                                    </div>
                                </div>
                            </div>

                            <!-- 标签内容 -->
                            <div class="mb-4">
                                <h3 class="section-title">
                                    <i class="fas fa-list-check"></i>
                                    标签内容
                                </h3>
                                <div class="field-grid">
                                    <!-- 基础字段 -->
                                    <div class="field-card selected" data-field="qr">
                                        <div class="field-icon"><i class="fas fa-qrcode"></i></div>
                                        <div>
                                            <div><strong>二维码</strong></div>
                                            <small class="text-muted">包含资产完整信息的二维码</small>
                                        </div>
                                        <input type="checkbox" name="include_qr" checked style="margin-left: auto;">
                                    </div>
                                    
                                    <div class="field-card selected" data-field="name">
                                        <div class="field-icon"><i class="fas fa-tag"></i></div>
                                        <div>
                                            <div><strong>资产名称</strong></div>
                                            <small class="text-muted">显示资产的完整名称</small>
                                        </div>
                                        <input type="checkbox" name="include_name" checked style="margin-left: auto;">
                                    </div>
                                    
                                    <div class="field-card selected" data-field="number">
                                        <div class="field-icon"><i class="fas fa-hashtag"></i></div>
                                        <div>
                                            <div><strong>资产编号</strong></div>
                                            <small class="text-muted">唯一的资产识别编号</small>
                                        </div>
                                        <input type="checkbox" name="include_number" checked style="margin-left: auto;">
                                    </div>
                                    
                                    <!-- 扩展字段 -->
                                    <div class="field-card" data-field="category">
                                        <div class="field-icon"><i class="fas fa-tags"></i></div>
                                        <div>
                                            <div><strong>资产类别</strong></div>
                                            <small class="text-muted">资产所属的分类信息</small>
                                        </div>
                                        <input type="checkbox" name="include_category" style="margin-left: auto;">
                                    </div>
                                    
                                    <div class="field-card" data-field="department">
                                        <div class="field-icon"><i class="fas fa-building"></i></div>
                                        <div>
                                            <div><strong>所属部门</strong></div>
                                            <small class="text-muted">资产归属的部门</small>
                                        </div>
                                        <input type="checkbox" name="include_department" style="margin-left: auto;">
                                    </div>
                                    
                                    <div class="field-card" data-field="user">
                                        <div class="field-icon"><i class="fas fa-user"></i></div>
                                        <div>
                                            <div><strong>使用人</strong></div>
                                            <small class="text-muted">当前使用该资产的人员</small>
                                        </div>
                                        <input type="checkbox" name="include_user" style="margin-left: auto;">
                                    </div>
                                    
                                    <div class="field-card" data-field="location">
                                        <div class="field-icon"><i class="fas fa-map-marker-alt"></i></div>
                                        <div>
                                            <div><strong>存放位置</strong></div>
                                            <small class="text-muted">资产的物理位置</small>
                                        </div>
                                        <input type="checkbox" name="include_location" style="margin-left: auto;">
                                    </div>
                                    
                                    <div class="field-card" data-field="purchase_date">
                                        <div class="field-icon"><i class="fas fa-calendar-alt"></i></div>
                                        <div>
                                            <div><strong>购买日期</strong></div>
                                            <small class="text-muted">资产的购买时间</small>
                                        </div>
                                        <input type="checkbox" name="include_purchase_date" style="margin-left: auto;">
                                    </div>
                                    
                                    <div class="field-card" data-field="warranty">
                                        <div class="field-icon"><i class="fas fa-shield-alt"></i></div>
                                        <div>
                                            <div><strong>保修信息</strong></div>
                                            <small class="text-muted">保修期限或状态</small>
                                        </div>
                                        <input type="checkbox" name="include_warranty" style="margin-left: auto;">
                                    </div>
                                    
                                    <div class="field-card" data-field="serial_number">
                                        <div class="field-icon"><i class="fas fa-barcode"></i></div>
                                        <div>
                                            <div><strong>序列号</strong></div>
                                            <small class="text-muted">设备序列号或型号</small>
                                        </div>
                                        <input type="checkbox" name="include_serial_number" style="margin-left: auto;">
                                    </div>
                                    
                                    <div class="field-card" data-field="status">
                                        <div class="field-icon"><i class="fas fa-info-circle"></i></div>
                                        <div>
                                            <div><strong>资产状态</strong></div>
                                            <small class="text-muted">当前使用状态</small>
                                        </div>
                                        <input type="checkbox" name="include_status" style="margin-left: auto;">
                                    </div>
                                    
                                    <div class="field-card" data-field="value">
                                        <div class="field-icon"><i class="fas fa-dollar-sign"></i></div>
                                        <div>
                                            <div><strong>资产价值</strong></div>
                                            <small class="text-muted">购买价格或当前价值</small>
                                        </div>
                                        <input type="checkbox" name="include_value" style="margin-left: auto;">
                                    </div>
                                </div>
                            </div>

                            <!-- 自定义字段 -->
                            <div class="mb-4">
                                <h3 class="section-title">
                                    <i class="fas fa-plus-circle"></i>
                                    自定义字段
                                </h3>
                                <div class="custom-field-section" style="background: linear-gradient(135deg, #fef7ff 0%, #faf5ff 100%); border: 2px dashed #a855f7; border-radius: 12px; padding: 20px;">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <span style="color: #7c3aed; font-weight: 600;">添加自定义显示字段</span>
                                        <button type="button" class="btn btn-sm" id="add-custom-field" style="background: linear-gradient(135deg, #8b5cf6, #7c3aed); color: white; border: none; padding: 6px 12px; border-radius: 6px;">
                                            <i class="fas fa-plus"></i> 添加字段
                                        </button>
                                    </div>
                                    <div id="custom-fields-container">
                                        <!-- 自定义字段将在这里动态添加 -->
                                    </div>
                                </div>
                            </div>

                            <!-- 模板设置 -->
                            <div class="mb-4">
                                <h3 class="section-title">
                                    <i class="fas fa-cog"></i>
                                    模板设置
                                </h3>
                                <div class="field-grid">
                                    <div class="field-card" data-field="public">
                                        <div class="field-icon"><i class="fas fa-globe"></i></div>
                                        <div>
                                            <div><strong>公共模板</strong></div>
                                            <small class="text-muted">允许其他用户使用</small>
                                        </div>
                                        <input type="checkbox" name="is_public" style="margin-left: auto;">
                                    </div>
                                    
                                    <div class="field-card" data-field="default">
                                        <div class="field-icon"><i class="fas fa-star"></i></div>
                                        <div>
                                            <div><strong>默认模板</strong></div>
                                            <small class="text-muted">设为默认模板</small>
                                        </div>
                                        <input type="checkbox" name="is_default" style="margin-left: auto;">
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-4">
                <div class="designer-card">
                    <div class="designer-header">
                        <h3 class="section-title text-white mb-0">
                            <i class="fas fa-eye"></i>
                            实时预览
                        </h3>
                    </div>
                    
                    <div class="designer-body">
                        <div class="preview-section">
                            <div class="preview-label portrait" id="preview-label">
                                <div id="preview-content">
                                    <div class="preview-field company-header" id="preview-company-header" style="display: none;">XX科技有限公司</div>
                                    <div class="preview-field title" style="font-weight: bold; margin-bottom: 2px;">示例资产名称</div>
                                    <div class="preview-field" id="preview-number" style="margin-bottom: 1px;">编号: AS001</div>
                                    <div class="preview-field" id="preview-category" style="margin-bottom: 1px; display: none;">类别: 电脑设备</div>
                                    <div class="preview-field" id="preview-department" style="margin-bottom: 1px; display: none;">部门: IT部门</div>
                                    <div class="preview-field" id="preview-user" style="margin-bottom: 1px; display: none;">使用人: 张三</div>
                                    <div class="preview-field" id="preview-location" style="margin-bottom: 1px; display: none;">位置: 办公室A-101</div>
                                    <div class="preview-field" id="preview-purchase-date" style="margin-bottom: 1px; display: none;">购买: 2024-01-01</div>
                                    <div class="preview-field" id="preview-warranty" style="margin-bottom: 1px; display: none;">保修: 2年</div>
                                    <div class="preview-field" id="preview-serial-number" style="margin-bottom: 1px; display: none;">序列号: SN123456</div>
                                    <div class="preview-field" id="preview-status" style="margin-bottom: 1px; display: none;">状态: 在用</div>
                                    <div class="preview-field" id="preview-value" style="margin-bottom: 1px; display: none;">价值: ¥5000</div>
                                    <div class="preview-field footer" id="preview-lost-notice" style="display: none;">如有遗失请联系 400-123-4567</div>
                                </div>
                                <div class="preview-qr">QR</div>
                            </div>
                            <div class="text-muted small">
                                <i class="fas fa-info-circle"></i>
                                预览会根据设置实时更新
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <h6><i class="fas fa-print"></i> Brother PT-9500PC</h6>
                            <ul class="small text-muted mb-0">
                                <li>支持 6-36mm 标签宽度</li>
                                <li>180x180 dpi 分辨率</li>
                                <li>自动切割功能</li>
                                <li>纵向/横向打印</li>
                            </ul>
                        </div>
                        
                        <button type="button" class="btn-action btn-warning" id="test-print-btn">
                            <i class="fas fa-print"></i>
                            测试打印预览
                        </button>
                        
                        <button type="button" class="btn-action btn-success" id="save-btn">
                            <i class="fas fa-save"></i>
                            保存模板
                        </button>
                        
                        <a href="{% url 'assets:label_template_list' %}" class="btn-action btn-primary" style="text-decoration: none;">
                            <i class="fas fa-arrow-left"></i>
                            返回列表
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<!-- 确保Bootstrap JS加载 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 方向选择
    document.querySelectorAll('.orientation-card').forEach(card => {
        card.addEventListener('click', function() {
            document.querySelectorAll('.orientation-card').forEach(c => c.classList.remove('selected'));
            this.classList.add('selected');
            this.querySelector('input').checked = true;
            updatePreview();
        });
    });

    // 字段选择
    document.querySelectorAll('.field-card').forEach(card => {
        const checkbox = card.querySelector('input[type="checkbox"]');
        card.addEventListener('click', function(e) {
            if (e.target.type !== 'checkbox') {
                checkbox.checked = !checkbox.checked;
            }
            card.classList.toggle('selected', checkbox.checked);
            updatePreview();
        });
    });

    // 设置变化
    ['label-width', 'font-size', 'company_header', 'lost_notice'].forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('change', updatePreview);
            element.addEventListener('input', updatePreview);
        }
    });

    // 自定义字段管理
    let customFieldCount = 0;
    
    document.getElementById('add-custom-field').addEventListener('click', function() {
        customFieldCount++;
        const container = document.getElementById('custom-fields-container');
        const fieldDiv = document.createElement('div');
        fieldDiv.className = 'custom-field-item mb-3 p-3';
        fieldDiv.style.cssText = 'background: white; border: 1px solid #e5e7eb; border-radius: 8px;';
        fieldDiv.innerHTML = `
            <div class="row">
                <div class="col-md-4">
                    <label class="form-label">字段名称</label>
                    <input type="text" class="form-control" name="custom_field_name_${customFieldCount}" placeholder="例如：供应商">
                </div>
                <div class="col-md-6">
                    <label class="form-label">显示内容</label>
                    <input type="text" class="form-control" name="custom_field_value_${customFieldCount}" placeholder="例如：联想集团">
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="button" class="btn btn-danger btn-sm remove-custom-field" style="width: 100%;">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </div>
            </div>
        `;
        container.appendChild(fieldDiv);
        
        // 添加删除事件
        fieldDiv.querySelector('.remove-custom-field').addEventListener('click', function() {
            fieldDiv.remove();
            updatePreview();
        });
        
        // 添加输入事件监听
        fieldDiv.querySelectorAll('input').forEach(input => {
            input.addEventListener('input', updatePreview);
        });
        
        updatePreview();
    });

    // 更新预览
    function updatePreview() {
        const orientation = document.querySelector('input[name="orientation"]:checked').value;
        const previewLabel = document.getElementById('preview-label');
        previewLabel.className = `preview-label ${orientation}`;
        
        // 显示/隐藏公司抬头
        const companyHeader = document.querySelector('input[name="company_header"]').value;
        const companyHeaderEl = document.getElementById('preview-company-header');
        if (companyHeader.trim()) {
            companyHeaderEl.textContent = companyHeader;
            companyHeaderEl.style.display = 'block';
        } else {
            companyHeaderEl.style.display = 'none';
        }
        
        // 显示/隐藏遗失标签提示
        const lostNotice = document.querySelector('input[name="lost_notice"]').value;
        const lostNoticeEl = document.getElementById('preview-lost-notice');
        if (lostNotice.trim()) {
            lostNoticeEl.textContent = lostNotice;
            lostNoticeEl.style.display = 'block';
        } else {
            lostNoticeEl.style.display = 'none';
        }
        
        // 更新各字段显示状态
        const fieldMappings = {
            'include_number': 'preview-number',
            'include_category': 'preview-category', 
            'include_department': 'preview-department',
            'include_user': 'preview-user',
            'include_location': 'preview-location',
            'include_purchase_date': 'preview-purchase-date',
            'include_warranty': 'preview-warranty',
            'include_serial_number': 'preview-serial-number',
            'include_status': 'preview-status',
            'include_value': 'preview-value'
        };
        
        Object.keys(fieldMappings).forEach(fieldName => {
            const checkbox = document.querySelector(`input[name="${fieldName}"]`);
            const previewEl = document.getElementById(fieldMappings[fieldName]);
            if (checkbox && previewEl) {
                previewEl.style.display = checkbox.checked ? 'block' : 'none';
            }
        });
        
        // QR码显示
        const qrElement = previewLabel.querySelector('.preview-qr');
        qrElement.style.display = document.querySelector('input[name="include_qr"]').checked ? 'flex' : 'none';
    }

    // 测试打印
    document.getElementById('test-print-btn').addEventListener('click', function() {
        const formData = new FormData(document.getElementById('label-form'));
        const data = Object.fromEntries(formData);
        
        // 模拟打印预览
        const printWindow = window.open('', '_blank', 'width=400,height=600');
        printWindow.document.write(`
            <html>
                <head>
                    <title>标签打印预览</title>
                    <style>
                        body { font-family: 'Courier New', monospace; padding: 20px; }
                        .label { border: 2px solid #000; padding: 10px; width: 200px; margin: 20px auto; }
                        .qr { float: right; width: 30px; height: 30px; border: 1px solid #000; text-align: center; line-height: 30px; font-size: 10px; }
                    </style>
                </head>
                <body>
                    <h3>Brother PT-9500PC 打印预览</h3>
                    <div class="label">
                        ${data.include_qr ? '<div class="qr">QR</div>' : ''}
                        ${data.include_name ? '<div><strong>示例资产名称</strong></div>' : ''}
                        ${data.include_number ? '<div>编号: AS001</div>' : ''}
                        ${data.include_category ? '<div>类别: 电脑设备</div>' : ''}
                        ${data.include_department ? '<div>部门: IT部门</div>' : ''}
                        ${data.include_user ? '<div>使用人: 张三</div>' : ''}
                    </div>
                    <p>标签宽度: ${data.label_width}</p>
                    <p>打印方向: ${data.orientation === 'portrait' ? '纵向' : '横向'}</p>
                    <button onclick="window.print()">打印</button>
                    <button onclick="window.close()">关闭</button>
                </body>
            </html>
        `);
    });

    // 保存模板
    document.getElementById('save-btn').addEventListener('click', function() {
        const form = document.getElementById('label-form');
        const formData = new FormData(form);
        
        if (!formData.get('name')) {
            alert('请输入模板名称');
            return;
        }
        
        // 收集所有数据
        const data = {
            name: formData.get('name'),
            description: formData.get('description') || '',
            company_header: formData.get('company_header') || '',
            lost_notice: formData.get('lost_notice') || '',
            label_width: formData.get('label_width'),
            orientation: formData.get('orientation'),
            font_size: formData.get('font_size'),
            include_qr: formData.has('include_qr'),
            include_name: formData.has('include_name'),
            include_number: formData.has('include_number'),
            include_category: formData.has('include_category'),
            include_department: formData.has('include_department'),
            include_user: formData.has('include_user'),
            include_location: formData.has('include_location'),
            include_purchase_date: formData.has('include_purchase_date'),
            include_warranty: formData.has('include_warranty'),
            include_serial_number: formData.has('include_serial_number'),
            include_status: formData.has('include_status'),
            include_value: formData.has('include_value'),
            is_public: formData.has('is_public'),
            is_default: formData.has('is_default'),
            printer_model: 'pt-9500pc'
        };
        
        // 收集自定义字段
        const customFields = [];
        document.querySelectorAll('.custom-field-item').forEach((item, index) => {
            const nameInput = item.querySelector(`input[name^="custom_field_name_"]`);
            const valueInput = item.querySelector(`input[name^="custom_field_value_"]`);
            if (nameInput && valueInput && nameInput.value.trim() && valueInput.value.trim()) {
                customFields.push({
                    name: nameInput.value.trim(),
                    value: valueInput.value.trim()
                });
            }
        });
        data.custom_fields = customFields;
        
        // 发送保存请求
        fetch('{% url "assets:save_label_template" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                alert('模板保存成功！');
                window.location.href = '{% url "assets:label_template_list" %}';
            } else {
                alert('保存失败: ' + result.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('保存失败，请重试');
        });
    });

    // 初始化预览
    updatePreview();
});
</script>
{% endblock %}
